package com.gitee.wsl.compose.modifier.input

import androidx.compose.foundation.focusable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier


/**
 *  Extension function to get notified if the [Composable] is focused.
 *
 *  @param [hoverable] whether hovering is enabled and an indicator for focus.
 *  @param [focusable] whether focusing is enabled
 *  @param [interactionSource] the used [MutableInteractionSource] to indicate if a [Composable] is focused.
 *  @param [onChanged] called when the focus state changes
 *  @return the [Modifier] which contains the changes of focus indication.
 */
@Composable
fun Modifier.onFocusChanged(
    hoverable: Boolean = true,
    focusable: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    onChanged: (Boolean) -> Unit
): Modifier {
    val isHovered by interactionSource.collectIsHoveredAsState()
    val isFocused by interactionSource.collectIsFocusedAsState()

    val latestValue = remember(isHovered, isFocused) { isHovered || isFocused }

    LaunchedEffect(latestValue) {
        onChanged(latestValue)
    }

    return this.hoverable(
        interactionSource = interactionSource,
        enabled = hoverable
    ).focusable(
        interactionSource = interactionSource,
        enabled = focusable
    )
}